import { getToken, getTokenKey } from '@/utils/auth'
import { baseUrl } from '@/config'

let timeout = 60 * 1000

const upRequest = (config: any) => {
  // 是否需要设置 token
  const token = getToken()
  config.header = config.header || {}
  if (token) {
    config.header[getTokenKey()] = token
  }
  return new Promise<any>((resolve: any, reject: any) => {
    uni.uploadFile({
      url: baseUrl + config.url,
      fileType: 'image',
      filePath: config.filePath,
      header: config.header,
      formData: {
        fileName: config.fileName,
      },
      timeout: config.timeout || timeout,
      name: 'file',
      success: ({ data, statusCode }) => {
        if (statusCode === 200) {
          const res = JSON.parse(data)
          if (res.code === '0') {
            return resolve(res)
          } else {
            return reject(res)
          }
        }
      },
      fail: (error: any) => {
        return reject({ tips: "上传失败" })
      }
    })
  })
}

export default upRequest